package org.viva.core.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

public class VerifyHandler {

	private static final int	width	= 60, height = 20;

	public static String createVerify() throws Exception {
		Random random = new Random();
		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
		}
		return sRand;
	}

	public static void saveVerify(String verify, HttpSession session) {
		session.setAttribute("randchk", verify);
		session.setAttribute("randchk_time", System.currentTimeMillis());
	}

	public static BufferedImage getImg(String str) {
		Random random = new Random();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}
		char[] cs = str.toCharArray();
		for (int i = 0; i < cs.length; i++) {
			g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(String.valueOf(cs[i]), 13 * i + 6, 16);
		}
		g.dispose();
		return image;
	}

	private static Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255) fc = 255;
		if (bc > 255) bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	public static String getVerify(HttpSession session) {
		return (String) session.getAttribute("randchk");
	}

	public static JSONObject checkVerify(String verify, HttpSession session) {
		JSONObject json = new JSONObject();
		String randchk = (String) session.getAttribute("randchk");
		Long randchk_time = (Long) session.getAttribute("randchk_time");
		if (randchk == null) {
			json.put("flag", false);
			json.put("msg", "验证码超时，请重新生成验证码!");
			cleanVerify(session);
		} else if (Math.abs(randchk_time - System.currentTimeMillis()) > (1000 * 60)) {
			json.put("flag", false);
			json.put("msg", "验证码超时，请重新生成验证码!");
			cleanVerify(session);
		} else if (!randchk.equals(verify)) {
			json.put("flag", false);
			json.put("msg", "验证码校验错误");
			cleanVerify(session);
		} else {
			json.put("flag", true);
		}
		return json;
	}

	public static void cleanVerify(HttpSession session) {
		session.removeAttribute("randchk");
		session.removeAttribute("randchk_time");
	}
}
